using B.S.BaseData.ErrorCode;
using B.S.BaseData.ErrorCode.ErrorCodes;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.ReadAPI.Applications.Commands.Users;
using B.S.BaseData.ReadAPI.Dtos.Users;
using B.S.DataBase.EFCoreServiers.Dtos.Meetings;
using B.S.DataBase.EFCoreServiers.IServices.Users;
using Lazy.Captcha.Core;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
using System.Threading.Tasks;

namespace B.S.BaseData.ReadAPI.Controllers
{
    /// <summary>
    /// 用户控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    [ApiExplorerSettings(GroupName = "Users")]
    public class UserController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<UserController> _logger;
        private readonly ICaptcha _captcha;
        private readonly IUserServices user;
        private readonly IUserRepository repository;

        public UserController(IMediator mediator, ILogger<UserController> logger, ICaptcha _captcha1, IUserServices user,IUserRepository repository)
        {
            _mediator = mediator;
            _logger = logger;
            _captcha = _captcha1;
            this.user = user;
            this.repository = repository;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginDto">登录信息</param>
        /// <returns>登录结果</returns>
        [HttpPost]
        public async Task<ActionResult<ApiResult<LoginResponseDto>>> Login([FromBody] LoginDto loginDto)
        {
            try
            {

                _logger.LogInformation($"收到用户 {loginDto.UserName} 的登录请求");

                if (loginDto == null)
                {
                    _logger.LogWarning("登录请求数据为空");
                    return BadRequest(ApiResult<LoginResponseDto>.Fail("登录信息不能为空", StatusCodeEnum.Fail));
                }

                var command = new LoginCommand { LoginDto = loginDto };
                var result = await _mediator.Send(command);

                if (!result.IsSuc)
                {
                    _logger.LogWarning($"用户 {loginDto.UserName} 登录失败: {result.Msg}");
                    return BadRequest(result);
                }

                _logger.LogInformation($"用户 {loginDto.UserName} 登录成功");
                return Ok(result);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, $"用户 {loginDto?.UserName} 登录过程中发生异常");
                return StatusCode(500, ApiResult<LoginResponseDto>.Fail("登录过程中发生错误，请稍后重试", StatusCodeEnum.Exception));
            }
        }

        /// <summary>
        /// 获取用户列表（分页、条件查询）
        /// </summary>
        [HttpGet]
        public async Task<ActionResult<ApiResult<ApiPaging<GetUserReponseDto>>>> GetUserList([FromQuery] GetUserDto dto)
        {
            var command = new GetUserCommand { Query = dto };
            var result = await _mediator.Send(command);
            return Ok(result);
        }





        /// <summary>
        /// 图片验证码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Captcha(string id)
        {
            var info = _captcha.Generate(id);
            // 有多处验证码且过期时间不一样，可传第二个参数覆盖默认配置。
            //var info = _captcha.Generate(id,120);
            var stream = new MemoryStream(info.Bytes);
            return File(stream, "image/gif");
        }

        /// <summary>
        /// 演示时使用HttpGet传参方便，这里仅做返回处理
        /// </summary>
        [HttpGet]
        public bool Validate(string id, string code)
        {
            return _captcha.Validate(id, code);
        }

        /// <summary>
        /// 多次校验（https://gitee.com/pojianbing/lazy-captcha/issues/I4XHGM）
        /// 演示时使用HttpGet传参方便，这里仅做返回处理
        /// </summary>
        [HttpGet]
        public ApiResult Validate2(string id, string code)
        {
            var res = _captcha.Validate(id, code, false);
            if (res == true)
                return ApiResult.Success(StatusCodeEnum.Ok);
            else
                return ApiResult.Fail("验证码错误",StatusCodeEnum.Ok);

        }

        /* /// <summary>
         /// 导出用户信息
         /// </summary>
         /// <param name="dto">查询条件</param>
         /// <returns>Excel文件流</returns>
         [HttpGet]
         public async Task<IActionResult> ExportUsers([FromQuery] GetUserDto dto)
         {
             try
             {
                 _logger.LogInformation("开始导出用户信息");

                 // 使用现有的查询命令获取数据，但不分页
                 dto.pageSize = int.MaxValue;  // 获取所有数据
                 dto.pageIndex = 1;

                 var command = new GetUserCommand { Query = dto };
                 var result = await _mediator.Send(command);

                 if (!result.IsSuc || result.Data?.Data == null)
                 {
                     _logger.LogWarning("导出用户信息失败: {Message}", result.Msg);
                     return BadRequest(ApiResult.Fail("获取用户数据失败", StatusCodeEnum.Fail));
                 }

                 // 创建Excel包
                 using var package = new ExcelPackage();
                 var worksheet = package.Workbook.Worksheets.Add("用户信息");

                 // 设置表头
                 worksheet.Cells[1, 1].Value = "用户ID";
                 worksheet.Cells[1, 2].Value = "用户名";
                 worksheet.Cells[1, 3].Value = "手机号";
                 worksheet.Cells[1, 4].Value = "会员等级";
                 worksheet.Cells[1, 5].Value = "消费金额";
                 worksheet.Cells[1, 6].Value = "可用积分";
                 worksheet.Cells[1, 7].Value = "注册渠道";
                 worksheet.Cells[1, 8].Value = "订单数量";
                 worksheet.Cells[1, 9].Value = "用户状态";
                 worksheet.Cells[1, 10].Value = "性别";
                 worksheet.Cells[1, 11].Value = "城市";
                 worksheet.Cells[1, 12].Value = "职业";

                 // 填充数据
                 var row = 2;
                 foreach (var user in result.Data.Data)
                 {
                     worksheet.Cells[row, 1].Value = user.UserId;
                     worksheet.Cells[row, 2].Value = user.UserName;
                     worksheet.Cells[row, 3].Value = user.Phone;
                     worksheet.Cells[row, 4].Value = user.MembershipLevel;
                     worksheet.Cells[row, 5].Value = user.ConsumptionAmount;
                     worksheet.Cells[row, 6].Value = user.AvailablePoints;
                     worksheet.Cells[row, 7].Value = user.RegistrationChannel;
                     worksheet.Cells[row, 8].Value = user.OrderLogs;
                     worksheet.Cells[row, 9].Value = user.IsEnabled ? "正常" : "禁用";
                     worksheet.Cells[row, 10].Value = user.Gender;
                     worksheet.Cells[row, 11].Value = user.City;
                     worksheet.Cells[row, 12].Value = user.Occupation;
                     row++;
                 }

                 // 设置列宽自适应
                 worksheet.Cells.AutoFitColumns();

                 // 设置表头样式
                 using (var range = worksheet.Cells[1, 1, 1, 12])
                 {
                     range.Style.Font.Bold = true;
                     range.Style.Fill.PatternType = ExcelFillStyle.Solid;
                     range.Style.Fill.BackgroundColor.SetColor(Color.LightGray);
                     range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                 }

                 // 生成文件流
                 var stream = new MemoryStream();
                 await package.SaveAsAsync(stream);
                 stream.Position = 0;

                 // 生成文件名
                 string fileName = $"用户信息_{DateTime.Now:yyyyMMddHHmmss}.xlsx";

                 _logger.LogInformation("用户信息导出成功，共 {Count} 条记录", result.Data.Data.Count);

                 return File(
                     stream,
                     "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                     fileName
                 );
             }
             catch (Exception ex)
             {
                 _logger.LogError(ex, "导出用户信息时发生异常");
                 return StatusCode(500, ApiResult.Fail("导出用户信息失败", StatusCodeEnum.Exception));
             }
         }*/
        /*
                /// <summary>
                /// 获取用户列表
                /// </summary>
                /// <param name="getUser"></param>
                /// <returns></returns>
                [HttpGet]
                public async Task<ApiResult<ApiPaging<GetUserReponseDtos>>> GetUser([FromQuery]GetUserDtos getUser)
                {
                      return await user.GetUser(getUser);
                }
        */
        /// <summary>
        /// 导出用户信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ExportUser() 
        {
            //获取数据
            var data = await repository.GetAll().ToListAsync();

            //调用
            var fileBytes = repository.ExportToExcelMy(data, "用户管理数据导出");


            string fileName = $"导出数据_{DateTime.Now:yyyyMMddHHmmss}.xlsx";

            return File(
                fileBytes,
                System.Net.Mime.MediaTypeNames.Application.Octet,
                fileName
            );
        }

        /*ExportToExcelMy*/


    }
}